<?php 

function generatePass($length){
	$str_abc  = "QAZXSWEDCVFRTGBNHYUJMKIOLPqwertyuioplkjhgfdsazxcvbnm0147852369!@#$%^&*()_";

	$pass = "";

	for ($i=0; $i < $length; $i++) { 
		$pos = rand(0,strlen($str_abc)-1);
		$let = $str_abc[$pos];
		$pass .=$let;
	}

	return $pass;

}


function DebugOut($var, $mode, $hr){
	global $DEBUG_MODE;
	if($DEBUG_MODE){
		if($mode){

			if($hr){
				echo "<hr>";
				var_dump($var);
				echo "<hr>";
			}else{
				var_dump($var);
				echo "<br>";	
			}
			
		}else{
			if($hr){
				echo "<hr>";
				echo $var;
				echo "<hr>";
			}else{
				echo $var;
				echo "<br>";
			}
			
		}	
	}
}


function invalidUser(){
	$user = UsersORM::getUser();
	if(isset($user["id"])){
		//DebugOut( "valid",1,0);	
		return false;
	}	
	//DebugOut("invalid",1,0);
	return true;
}



class UsersORM
	{
		public static function getUser($DEBUG = false){
			global $wpdb;
			$prefix = 'timetable_';
			$current_user = wp_get_current_user(); 
			if( isset($current_user->data) ){
				$id = $current_user->data->ID;	
				//$query_user = "SELECT iduser id, role_name, role_status FROM {$prefix}user, {$prefix}role WHERE wp_user_id = $id AND idrole=role_id";
				$user_id_query =  "SELECT iduser user_id FROM timetable_user WHERE wp_user_id = $id ";
				$user_id = $wpdb->get_row($user_id_query, ARRAY_A);
				$user_id = $user_id['user_id'];
				if ($user_id == '') {
					$user_res = array(
							"id"=>0,
							'role_name'=>'',
							"role_status" => 6
						);
					if($current_user->caps["administrator"]){
						$user_res = array(
							"id"=>0,
							'role_name'=>'Admin',
							"role_status" => 1
						);
					}
				}else{
					$query_user = "SELECT 
								iduser id, role_name, role_status, 
								(SELECT idclient FROM {$prefix}client WHERE user_id= $user_id ) client_id, 
								(SELECT client_name FROM {$prefix}client WHERE user_id= $user_id ) client_name, 
								(SELECT idteacher FROM {$prefix}teacher WHERE user_id = $user_id ) teacher_id,
								(SELECT teacher_name FROM {$prefix}teacher WHERE user_id = $user_id ) teacher_name 
								FROM {$prefix}user, {$prefix}role WHERE wp_user_id = $id AND idrole=role_id";
					$user_res = $wpdb->get_row($query_user, ARRAY_A);
				}
				if($DEBUG){
					//return $query_user;
				}	
				return $user_res ;
			}else{
				$id = 0;	
				return  $id;
			}
		}

	}

class ClientORM
{
	public $role;
	public $isclient;
	public $isteacher;
	public $isadmin;
	public $user;
	public $courses;

	public $prefix = 'timetable_';

	public function __construct(){
		global $wpdb;
		$prefix = $this->prefix;
		$this->user = UsersORM::getUser();
		$user = $this->user;

		if($user == 0){
			$role_query = "SELECT idrole role_id,  role_name, role_status FROm {$prefix}role WHERE role_status = 5";
			$this->role = $wpdb->get_row($role_query, ARRAY_A);

		}else{
			$this->role = array(
					"role_name" => $user['role_name'],
					"role_status" => $user['role_status']
				);
			if($this->role["role_status"] >= 5){
				$this->isclient = true;
				$this->isteacher = false;
				$this->isadmin = false;
			}elseif($this->role["role_status"] <= 2){
				$this->isclient = false;
				$this->isteacher = false;
				$this->isadmin = true;
			}else{
				$this->isclient = false;
				$this->isteacher = true;
				$this->isadmin = false;
			}
		}	
	}

	public function all_courses(){
		global $wpdb;
		$prefix = $this->prefix;
		$query = "SELECT idcourse course_id, course_name FROM {$prefix}course";
		$res = $wpdb->get_results($query, ARRAY_A);	
	}

	public function courses(){
		global $wpdb;

		$res = '';
		//return json_encode($this->user["client_id"]);
		$prefix = $this->prefix;
		if($this->isclient){
			$client_id = $this->user['client_id'];
			$query = "SELECT idclientcourse clientcourse_id, course_name FROM {$prefix}clientcourse, {$prefix}course  WHERE  course_id = idcourse AND client_id = $client_id";
			$res = $wpdb->get_results($query, ARRAY_A);
		}elseif ($this->isteacher) {
			$teacher_id = $this->user['teacher_id'];
			$query = "SELECT idclientcourse clientcourse_id, course_name FROM {$prefix}clientcourse, {$prefix}course  WHERE  course_id = idcourse AND teacher_id = $teacher_id";
			$res = $wpdb->get_results($query, ARRAY_A);
		}else{
			$res = '';
		}

		return json_encode($res);

	}

}

class ViewORM
{
	public $view_name;
	public $name;
	public $table;
	public $class;
	public $table_array;
	public $fields_all;
	public $fields_view;
	public $where;
	public $update_options;
	public $delete_options;
	public $insert_options;
	public $structure;
	public $required_tables;
	public $access;
	public $granted;
	public $get_all;
	public $user;
	public $role_status;
	public $pagination;
	
	public $prefix = "timetable_";

	public function __construct($view_name){
		$this->assoc($view_name);
	}

	

	private function assoc($view_name){
		global $wpdb;
		$prefix = $this->prefix;
		$assoc_array= array(
				'clientcourse' =>array(
						"pagination" => 5,
						"required_tables"=>array('role', 'wp_user'),
						"table"=>"custom",
						"get_all"=>
							"SELECT 
  							  idclientcourse, 
							  course_id,
							  course_name,
							  course_basecost,
							  paystatus_id,
							  paystatus_name,
							  teacher_id,
							  teacher_name,
							  clientcourse_lessontotal,
							  clientcourse_count,
							  client_id,
							  client_name,
							  client_contact,
							  ROUND((SELECT SUM(payment_amount) FROM `timetable_payment` WHERE clientcourse_id = idclientcourse AND status='SUCCESS')/course_basecost*100, 1) clientcourse_paid,
							  (SELECT SUM(payment_amount) FROM `timetable_payment` WHERE clientcourse_id = idclientcourse AND status='SUCCESS') clientcourse_paid_summ,
							  if(    
							    (ifnull( (SELECT SUM( payment_amount ) FROM timetable_payment WHERE clientcourse_id = idclientcourse AND status = 'SUCCESS' ), 0)
							        /
							    (SELECT course_basecost FROM timetable_course WHERE idcourse = course_id ) ) < 1,
							       1,0 
							  ) needpay, 
							  clientcourse_adress,
							  clientcourse_note,
							  form_id,
							  form_name,
							  DATE_FORMAT(clientcourse_begin,'%d-%m-%Y') clientcourse_begin

							FROM 
							  {$prefix}clientcourse,
							  {$prefix}course, 
							  {$prefix}client,
							  {$prefix}paystatus,
							  {$prefix}teacher,
							  {$prefix}form
							WHERE
							    course_id = idcourse
							  	AND paystatus_id = idpaystatus 
							  	AND teacher_id = idteacher
							  	AND client_id = idclient
							  	AND form_id = idform
							",
						"structure"=>array(
							"idclientcourse"=>"", 
							"course_id"=>"",
							"course_name"=>"",
							"course_basecost"=>"",
							"paystatus_id"=>"",
							"paystatus_name"=>"",
							"teacher_id"=>"",
							"teacher_name"=>"",
							"clientcourse_lessontotal"=>"",
							"clientcourse_lessoncount"=>"",
							"clientcourse_count"=>"",
							//"coursestatus_id"=>"",
							"coursestatus_name"=>"",
							"client_id"=>"",
							"client_name"=>"",
							"clientcourse_begin"=>"",
							"form_id"=>"",
							"form_name"=>"",
							  "client_contact"=>"",
							  "clientcourse_paid"=>"",
							  "clientcourse_adress"=>"",
							  "clientcourse_note"=>""
							//"clientcourse_end"=>"",
							//"timetable_id"=>""
						),		
						"update_options"=>array(
							"where"=>array("idclientcourse"),
							"where_format"=>array('%d'),
							"set"=>array(
								"course_id", 
								"paystatus_id",
								"teacher_id",
								"clientcourse_lessontotal",
								"clientcourse_count",
								"client_id",
								"clientcourse_begin",
								"form_id",
								
								"clientcourse_paid",
								"clientcourse_adress",
								"clientcourse_note"
								),
							"set_c" => array(
								"course_id", 
								"paystatus_id",
								"teacher_id",
								"clientcourse_lessontotal",
								"clientcourse_count",
								"client_id",
								"clientcourse_begin",
								"idclientcourse",
								"form_id",

							    "clientcourse_paid",
							    "clientcourse_adress",
							    "clientcourse_note"

								),
							"set_format"=>array('%d','%d'),
							"table"=>"{$prefix}clientcourse",
							"query"=>"UPDATE {$prefix}clientcourse SET 
								course_id = %s,
								paystatus_id = %s,
								teacher_id = %s,
								clientcourse_lessontotal = %s,
								clientcourse_count = %s,
								client_id = %s,
								clientcourse_begin = STR_TO_DATE('%s', '^d-^m-^Y'),
								form_id = %s,
								  clientcourse_paid = %s,
								  clientcourse_adress = '%s',
								  clientcourse_note = '%s'
							 WHERE idclientcourse = %s"
							),
						"insert_options" =>array(
							"set"=>array(
									"course_id", 
									"teacher_id",
									"clientcourse_lessontotal",
									"clientcourse_count",
									"client_id",
									"clientcourse_begin",
									"form_id",
  								    "clientcourse_paid",
									"clientcourse_adress",
									"clientcourse_note"	
									),
							  "query"=>"INSERT INTO {$prefix}clientcourse (course_id,teacher_id, clientcourse_lessontotal,clientcourse_count, client_id,clientcourse_begin,form_id, clientcourse_paid, clientcourse_adress, clientcourse_note) VALUES(%s,%s,%s,%s,%s,STR_TO_DATE('%s', '^d-^m-^Y'),%s,%s,'%s','%s')"
							),
						"delete_options" => array(
							"where"=>array("idclientcourse"),
							"table"=>"{$prefix}clientcourse",
							"query"=>"DELETE FROM {$prefix}clientcourse WHERE idclientcourse= %s"
							),
						"header" => array(
								"client_name"=>array(
									"name"=>"Клиент",
									"place"=>"main",
									"format"=>'s',
									"select_name"=>"client",
									"key"=>array(
										"table" => "SELECT idclient client_id, client_name FROM {$prefix}client",
										"id" => "client_id",
										"field" => "client_name"
										)
									),
								"course_name"=>array(
									"name"=>"Курс",
									"format"=>'select',
									"place"=>"main",
									"select_name"=>"course",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "course_id",
										"field" => "course_name"
										)
									),
								"clientcourse_begin"=>array(
									"name"=>"Дата начала занятий",
									"place"=>"main",
									"format"=>'date',
									"key" => array(
										"field"=>"clientcourse_begin"
										)
									),
								"clientcourse_lessontotal"=>array(
									"name"=>"Количество занятий(общее)",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"clientcourse_lessontotal"
										)
									),
								"clientcourse_lessoncount"=>array(
									"name"=>"Количество занятий",
									"place"=>"main",
									"format"=>'c',
									"fields"=>array(
											"clientcourse_count",
											"clientcourse_lessontotal"
									    ),
									"key" => array(
										"field"=>"clientcourse_lessoncount"
										)
									),
								"teacher_name"=>array(
									"name"=>"Преподователь",
									"format"=>'select',
									"place"=>"main",
									"select_name"=>"teacher",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "teacher_id",
										"field" => "teacher_name"
										)
									),
								"course_basecost"=>array(
									"name"=>"Сумма(стоимость)",
									"place"=>"add",
									"format"=>'s',
									"key" => array(
										"field"=>"course_basecost"
										)
									),
								
								"form_name"=>array(
									"name"=>"Форма обучение",
									"place"=>"add",
									"format"=>'select',
									"select_name"=>"form",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "form_id",
										"field" => "form_name"
										) 
									),
								"client_contact"=>array(
										"name"=>"Контакты",
										"place"=>"add",
										"format"=>'t',
										"key"=>array(
												"field"=>"client_contact"
											)
									),
							  	"clientcourse_adress"=>array(
							  			"name"=>"Адрес проведения",
							  			"place"=>"add",
							  			"format"=>'t',
							  			"key"=>array(
							  					"field"=>"clientcourse_adress"
							  				)
							  		),
							  	"clientcourse_paid"=>array(
							  			"name"=>"Оплата",
							  			"place"=>"add",
							  			"format"=>'d',
							  			"key"=>array(
							  					"field"=>"clientcourse_paid"
							  				)
							  		),
							  	"clientcourse_note"=>array(
							  			"name"=>"Дполнительно",
							  			"place"=>"add",
							  			"format"=>'t',
							  			"key"=>array(
							  					"field"=>"clientcourse_note"
							  				)
							  		),
							),
						"name"=>"Курсы клиентов",
						"class"=>"clientcourseView",
						'access'=>5
					),

				'user' =>array(
						"pagination"=>8,
						"required_tables"=>array('role', 'wp_user'),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								iduser, 
								wp_user_id,
								display_name,
								role_id,
								role_name
							FROM 
								{$prefix}user,
								$wpdb->users,
								{$prefix}role
							WHERE
								wp_user_id = ID
								AND role_id = idrole",
						"structure"=>array(
								"iduser"=>"", 
								"wp_user_id"=>"",
								
								"display_name"=>"",
								"role_id"=>"",
								"role_name"=>""
						),		
						"update_options"=>array(
							"where"=>array("iduser"),
							"where_format"=>array('%d'),
							"set"=>array("wp_user_id", "role_id"),
							"set_format"=>array('%d','%d'),
							"table"=>"{$prefix}user",
							"query"=>"UPDATE {$prefix}user SET wp_user_id = %s, role_id = %s WHERE iduser = %s"
							),
						"insert_options" =>array(
							"set"=>array("wp_user_id", "role_id"),
							"query"=>"INSERT INTO {$prefix}user (wp_user_id, role_id) VALUES(%s,%s)"
							),
						"delete_options" => array(
							"where"=>array("iduser"),
							"table"=>"{$prefix}user",
							"query"=>"DELETE FROM {$prefix}user WHERE iduser = %s"
							),
						"header" => array(
								
								"display_name"=>array(
									"name"=>"Пользователь",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"wp_users",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "wp_user_id",
										"field" => "display_name"
										)
									),
								"role_name"=>array(
									"name"=>"Роль",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"role",
									"key"=>array(
										"table" => "SELECT idrole role_id, role_name FROM {$prefix}role",
										"id" => "role_id",
										"field" => "role_name"
										)
									)
							),
						"name"=>"Пользователи",
						"class"=>"userView",
						'access'=>2	
					),
					
					'role' =>array(
						"required_tables"=>array(),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idrole, 
								role_name,
								role_status
							FROM 
								{$prefix}role",
						"structure"=>array(
								"idrole"=>"", 
								"role_name"=>"",
								"role_status"=>"",
						),		
						"update_options"=>array(
							"where"=>array("idrole"),
							"where_format"=>array('%d'),
							"set"=>array("role_name","role_status"),
							"set_format"=>array('%s','%d'),
							"table"=>"{$prefix}role",
							"query"=>"UPDATE {$prefix}role SET role_name = '%s', role_status = %s WHERE idrole = %s"
							),
						"insert_options" =>array(
							"set"=>array("role_name", "role_status"),
							"query"=>"INSERT INTO {$prefix}role (role_name, role_status) VALUES('%s',%s)"
							),
						"delete_options" => array(
							"where"=>array("idrole"),
							"table"=>"{$prefix}role",
							"query"=>"DELETE FROM {$prefix}role WHERE idrole = %s"
							),
						"header" => array(
								"role_name"=>array(
									"name"=>"Роль",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"role_name"
										)
									),
								"role_status"=>array(
									"name"=>"Статус",
									"place"=>"main",
									"format"=>'d',
									"key" => array(
										"field"=>"role_status"
										)
									)
							),
						"name"=>"Роль",
						
						"class"=>"roleView",
						'access'=>2
						),						
					'teacher' =>array(
						"required_tables"=>array('user'),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idteacher, 
								teacher_name,
								user_id,
								teacher_account,					
								(SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name
							FROM 
								{$prefix}teacher,
                                {$prefix}user
								WHERE
								   iduser = user_id",
						"structure"=>array(
								"idteacher"=>"", 
								"teacher_name"=>"",
								"user_id"=>"",
								"user_name"=>"",
								"teacher_account"=>""
						),		
						"insert_options" =>array(
							"set"=>array("teacher_name", "user_id", "teacher_account"),
							"query"=>"INSERT INTO {$prefix}teacher (teacher_name, user_id, teacher_account) VALUES('%s',%s, '%s')"
							),
						"delete_options" => array(
							"where"=>array("idteacher"),
							"table"=>"{$prefix}teacher",
							"query"=>"DELETE FROM {$prefix}teacher WHERE idteacher = %s"
							),
						"update_options"=>array(
							"where"=>array("idteacher"),
							"where_format"=>array('%d'),
							"set"=>array("teacher_name","user_id","teacher_account"),
							"set_format"=>array('%s','%d','%s'),
							"table"=>"{$prefix}teacher",
							"query"=>"UPDATE {$prefix}teacher SET teacher_name = '%s', user_id = %s, teacher_account='%s' WHERE idteacher = %s"
							),
						"header" => array(
								"teacher_name"=>array(
									"name"=>"Имя",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"teacher_name"
										)
									),
								"teacher_account"=>array(
									"name"=>"Реквизиты",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"teacher_account"
										)
									),
								
								"user_name"=>array(
									"name"=>"Пользователь",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"user_teacher",
									"key"=>array(
										"table" => "SELECT iduser user_id, (SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name FROM {$prefix}user",
										"id" => "user_id",
										"field" => "user_name"
										)
									)
								
							),
						"name"=>"Преподователи",
						
						"class"=>"teacherView",
						'access'=>2

					),						
					'client' =>array(
						"pagination"=>8,
						"required_tables"=>array('user'),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idclient, 
								client_name,
								user_id,
								client_contact,
								(SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name
							FROM 
								{$prefix}client,
                                {$prefix}user
								WHERE
								   iduser = user_id",
						"structure"=>array(
								"idclient"=>"", 
								"client_name"=>"",
								"client_contact"=>"",
								"user_id"=>"",
								"user_name"=>""
						),	
						"insert_options" =>array(
							"set"=>array("client_name", "user_id", "client_contact"),
							"query"=>"INSERT INTO {$prefix}client (client_name, user_id,client_contact) VALUES('%s',%s,'%s')"
							),
						"delete_options" => array(
							"where"=>array("idclient"),
							"table"=>"{$prefix}client",
							"query"=>"DELETE FROM {$prefix}client WHERE idclient = %s"
							),
						"update_options"=>array(
							"where"=>array("idclient"),
							"where_format"=>array('%d'),
							"set"=>array("client_name","user_id","client_contact"),
							"set_format"=>array('%s','%d','%s'),
							"table"=>"{$prefix}client",
							"query"=>"UPDATE {$prefix}client SET client_name = '%s', user_id = %s, client_contact='%s' WHERE idclient = %s"
							),
						"header" => array(
								"client_name"=>array(
									"name"=>"Имя",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"client_name"
										)
									),
								"client_contact"=>array(
									"name"=>"Контакты",
									"place"=>"main",
									"format"=>'t',
									"key" => array(
										"field"=>"client_contact"
										)
									),
								"user_name"=>array(
									"name"=>"Пользователь",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"user_client",
									"key"=>array(
										"table" => "SELECT iduser user_id, (SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name FROM {$prefix}user",
										"id" => "user_id",
										"field" => "user_name"
										)
									)
								
							),
						"name"=>"Клиенты",
						"class"=>"clientView",
						'access'=>2

					),						
					'coursestatus' =>array(
						"required_tables"=>array('coursestatus'),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idcoursestatus, 
								coursestatus_name
							FROM 
								{$prefix}coursestatus",
						"structure"=>array(
								"idcoursestatus"=>"", 
								"coursestatus_name"=>""
						),
						"insert_options" =>array(
							"set"=>array("idcoursestatus", "coursestatus_name"),
							"query"=>"INSERT INTO {$prefix}coursestatus (idcoursestatus, coursestatus_name) VALUES(%s, '%s')"
							),
						"delete_options" => array(
							"where"=>array("idcoursestatus"),
							"table"=>"{$prefix}coursestatus",
							"query"=>"DELETE FROM {$prefix}coursestatus WHERE idcoursestatus = %s"
							),	
						"update_options"=>array(
							"where"=>array("idcoursestatus"),
							"where_format"=>array('%d'),
							"set"=>array("idcoursestatus", "coursestatus_name"),
							"set_format"=>array('%s'),
							"table"=>"{$prefix}coursestatus",
							"query"=>"UPDATE {$prefix}coursestatus SET idcoursestatus=%s, coursestatus_name = '%s' WHERE idcoursestatus = %s"
							),
						"header" => array(
								"idcoursestatus"=>array(
									"name"=>"ID",
									"place"=>"main",
									"format"=>'d',
									"key" => array(
										"field"=>"idcoursestatus"
										)
									),
								"coursestatus_name"=>array(
									"name"=>"Имя",
									"place"=>"main",
									"format"=>'s' ,
									"key" => array(
										"field"=>"coursestatus_name"
										)
									)
							),
						"name"=>"Статус курса",
						"class"=>"coursestatusView",
						'access'=>2	
					),
					'paystatus' =>array(
						"required_tables"=>array(),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idpaystatus, 
								paystatus_name
							FROM 
								{$prefix}paystatus",
						"structure"=>array(
								"idpaystatus"=>"", 
								"paystatus_name"=>""
						),	
						"insert_options" =>array(
							"set"=>array( "idpaystatus", "paystatus_name"),
							"query"=>"INSERT INTO {$prefix}paystatus ( idpaystatus, paystatus_name) VALUES(%s, '%s')"
							),
						"delete_options" => array(
							"where"=>array("idpaystatus"),
							"table"=>"{$prefix}paystatus",
							"query"=>"DELETE FROM {$prefix}paystatus WHERE idpaystatus = %s"
							),	
						"update_options"=>array(
							"where"=>array("idpaystatus"),
							"where_format"=>array('%d'),
							"set"=>array("idpaystatus", "paystatus_name"),
							"set_format"=>array('%s'),
							"table"=>"{$prefix}paystatus",
							"query"=>"UPDATE {$prefix}paystatus SET idpaystatus = %s  paystatus_name = '%s' WHERE idpaystatus = %s"
							),
						"header" => array(
								"idpaystatus"=>array(
									"place"=>"main",
									"name"=>"ID",
									"format"=>'d',
									"key" => array(
										"field"=>"idpaystatus"
										)
									),
								"paystatus_name"=>array(
									"name"=>"Имя",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"paystatus_name"
										)
									)
							),
						"name"=>"Статус оплаты",
						"class"=>"paystatusView",
						'access'=>2
					),
					'form' =>array(
						"required_tables"=>array(),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idform, 
								form_name
							FROM 
								{$prefix}form",
						"structure"=>array(
								"idform"=>"", 
								"form_name"=>""
						),	
						"insert_options" =>array(
							"set"=>array("form_name"),
							"query"=>"INSERT INTO {$prefix}form ( form_name) VALUES('%s')"
							),
						"delete_options" => array(
							"where"=>array("idform"),
							"table"=>"{$prefix}form",
							"query"=>"DELETE FROM {$prefix}form WHERE idform = %s"
							),	
						"update_options"=>array(
							"where"=>array("idform"),
							"where_format"=>array('%d'),
							"set"=>array("idform", "form_name"),
							"set_format"=>array('%s'),
							"table"=>"{$prefix}form",
							"query"=>"UPDATE {$prefix}form SET idform = %s,  form_name = '%s' WHERE idform = %s"
							),
						"header" => array(
								"form_name"=>array(
									"name"=>"Имя",
									"place"=>"main",
									"format"=>'s',
									"key"=>array(
										"field"=>"form_name"
										)
									)
							),
						"name"=>"Форма обучения",
						"class"=>"formView",
						'access'=>2
					),
					'course' =>array(
						"required_tables"=>array(),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idcourse, 
								course_name,
								course_basecost,
								course_totalcount
							FROM 
								{$prefix}course",
						"structure"=>array(
								"idcourse"=>"", 
								"course_name"=>"",
								"course_basecost"=>"",
								"course_totalcount"=>""
						),		
						"insert_options" =>array(
							"set"=>array("course_name","course_basecost","course_totalcount"),
							"query"=>"INSERT INTO {$prefix}course (course_name, course_basecost, course_totalcount) VALUES('%s',%s, %s)"
							),
						"delete_options" => array(
							"where"=>array("idcourse"),
							"table"=>"{$prefix}course",
							"query"=>"DELETE FROM {$prefix}course WHERE idcourse = %s"
							),	
						"update_options"=>array(
							"where"=>array("idcourse"),
							"where_format"=>array('%d'),
							"set"=>array("course_name", "course_basecost","course_totalcount"),
							"set_format"=>array('%s'),
							"table"=>"{$prefix}course",
							"query"=>"UPDATE {$prefix}course SET course_name = '%s', course_basecost = %s, course_totalcount = %s WHERE idcourse = %s"
							),
						"header" => array(
								"course_name"=>array(
									"name"=>"Название курса",
									"place"=>"main",
									"format"=>'s',
									"key" => array(
										"field"=>"course_name"
										)
									),
								"course_basecost"=>array(
									"name"=>"Базовая стоимость, руб.",
									"place"=>"main",
									"format"=>'d' ,
									"key" => array(
										"field"=>"course_basecost"
										)
									),
								"course_totalcount"=>array(
									"name"=>"Количество занятий",
									"place"=>"main",
									"format"=>'d' ,
									"key" => array(
										"field"=>"course_totalcount"
										)
									)
							),
						"name"=>"Курсы",
						"class"=>"courseView",
						'access'=>2
					),
					'teachercourse' =>array(
						"required_tables"=>array(),
						"table"=>"simple",
						"get_all"=>
							"SELECT 
								idteachercourse, 
								teacher_id,
								teacher_name,
								course_id,
								course_name
							FROM 
								{$prefix}teachercourse, {$prefix}teacher, {$prefix}course
							WHERE
								 teacher_id = idteacher AND course_id = idcourse",
						"structure"=>array(
								"idteachercourse" => "",
								"teacher_id" => "",
								"teacher_name" => "",
								"course_id" => "",
								"course_name" => ""
						),		
						"insert_options" =>array(
							"set"=>array("teacher_id","course_id"),
							"query"=>"INSERT INTO {$prefix}teachercourse (teacher_id, course_id) VALUES(%s ,%s)"
							),
						"delete_options" => array(
							"where"=>array("idteachercourse"),
							"table"=>"{$prefix}teachercourse",
							"query"=>"DELETE FROM {$prefix}teachercourse WHERE idteachercourse = %s"
							),	
						"update_options"=>array(
							"where"=>array("idteachercourse"),
							"where_format"=>array('%d'),
							"set"=>array("teacher_id","course_id"),
							"set_format"=>array('%s','%s'),
							"table"=>"{$prefix}teachercourse",
							"query"=>"UPDATE {$prefix}teachercourse SET teacher_id = '%s', course_id = %s WHERE idteachercourse = %s"
							),
						"header" => array(
								"teacher_name"=>array(
									"name"=>"Преподователь",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"teacher",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "teacher_id",
										"field" => "teacher_name"
										)
									),
								"course_name"=>array(
									"name"=>"Курс",
									"place"=>"main",
									"format"=>'select',
									"select_name"=>"course",
									"key"=>array(
										"table" => "SELECT ID wp_user_id, display_name FROM $wpdb->users",
										"id" => "course_id",
										"field" => "course_name"
										)
									)
							),
						"name"=>"Курсы Преподователей",
						"class"=>"teachercourseView",
						'access'=>2
					)

			);

		$view = $assoc_array[$view_name];
		$this->view_name = $view_name;
		$this->table = $view['table'];
		$this->name = $view['name'];
		$this->get_all = $view["get_all"];
		$this->header = $view['header'];
		$this->class = $view["class"];
		$this->update_options = $view["update_options"];
		$this->delete_options = $view["delete_options"];
		$this->insert_options = $view["insert_options"];
		$this->structure = $view["structure"];
		$this->required_tables = $view["required_tables"];
		$this->access = $view["access"];
		$user = UsersORM::getUser();
		if(isset($view['pagination'])){
			$this->pagination = $view['pagination'];
		}else{
			$this->pagination = 0;
		}



		$this->user = $user;
		$this->role_status = $user["role_status"];
		$this->granted = false;
		if($this->role_status <= $this->access){
			$this->granted = true;
		}
	}

	private function defaultValues($values){
		global $wpdb;
		$prefix = $this->prefix;
		if($this->view_name=='clientcourse'){
			if( $values['clientcourse_lessoncount'] =='' ){
				$course_id = $values['course_id'];
				$var = $wpdb->get_var("SELECT course_totalcount FROM {$prefix}course WHERE idcourse = $course_id");
				$values['clientcourse_lessontotal'] = $var;
			}

			if( $values['clientcourse_paid'] =='' ){
				$values['clientcourse_paid'] = '0';

			}
		}
		if($this->view_name=='client'){
			if( $values['client_name'] == '' ){
				$values['client_name'] = $values['user_name'];
			}
		}
	
		return $values;

	}

	private function postSelect($values){
		global $wpdb;
		$prefix = $this->prefix;
		return $values;
	}

	public function insert($values){
		
		global $wpdb;
	
		$DEBUG = false;
		
		$values = $this->defaultValues($values);

		if($DEBUG){

			$query_str = $this->insert_options["query"];
			$arg = array();
			foreach ($this->insert_options['set'] as $value) {
				$arg[] = $values[$value];
			}
			$query = vsprintf($query_str, $arg);
			$query = str_replace("^","%",$query);

			//$wpdb->query($query);
			return  $query;


		}else{
			$query_str = $this->insert_options["query"];



			$arg = array();
			foreach ($this->insert_options['set'] as $value) {
				$arg[] = $values[$value];
			}
			$query = vsprintf($query_str, $arg);
			$query = str_replace("^","%",$query);

			$res = $wpdb->query($query);
			return  $query;
		}
	}
    
	public function delete($values){
		
		global $wpdb;
		/*
		if( $this->granted == false ){
			return "";
		}
		*/

		$query_str = $this->delete_options["query"];
		$args = array();
		foreach ($this->delete_options['where'] as $value) {
			$args[] = $values[$value];
		}
		$query = vsprintf($query_str,$args);
		$wpdb->query($query);
		return  $query;
		
		//return "delete";
	}

	public function update($values){
		
		global $wpdb;
		/*
		if( $this->granted == false ){
			return "";
		}
		*/


		$query_str = $this->update_options["query"];

		$args_key = array_merge($this->update_options['set'],$this->update_options['where']);

		$args_val = array();
	
		foreach ($args_key as $key) {
			$args_val[] = $values[$key];
		}

		$query = vsprintf($query_str, $args_val);
		$query = str_replace("^","%",$query);
		$wpdb->query($query);
    	return  $query;
			

		//return json_encode($query_str);
		//return json_encode($args);
		//return json_encode($values);
		
		//return "update";
	}

	public function findAllQuery(){



		if($this->view_name=="clientcourse" && $this->role_status == 5 ){
			$client_id =  $this->user['client_id']; 
			return $query = $this->get_all. " AND client_id = $client_id ";
		}elseif($this->view_name=="clientcourse" && ( $this->role_status == 3 || $this->role_status == 4) ){
			$teacher_id = $this->user['teacher_id'];
			return $query = $this->get_all. " AND teacher_id = $teacher_id ";
		}elseif($this->role_status < 3){
			return $query = $this->get_all;
		}else{
			return "";
		}
	}

	public function findAll($num=false){
		global $wpdb;
	
		$tab_name = $this->prefix.$this->name;

		

		//$count =  $wpdb->get_var("SELECT COUNT(*) FROM {$view->prefix}{$view->view_name}");

		/*if($count == 0){
			return array();
		}
		*/

		$query = $this->findAllQuery();

		if($query == ""){
			return "";
		}

		$results = $wpdb->get_results($query,ARRAY_A);
		if($num){	
			$results = $wpdb->get_results($query,ARRAY_N);	
		}

		$results = $this->postSelect($results);
		
		return $results;
	}

	public function findWhere($searchkey){
		global $wpdb;
		$query = $this->findAllQuery();
		if($query != ''){
			$query .= " AND ( client_name like '%{$searchkey}%' OR teacher_name like '%{$searchkey}%')";	
		}
		$results = $wpdb->get_results($query,ARRAY_A);
		//return $query;
		return $results;
	}

	public function getView(){


		$body=$this->findAll();
		
				$header = array();
				foreach ($this->header as $key_header => $value_header) {
					$header[$key_header] = $value_header['format'];
				}
				$result = array(
						
						"head"=>$header,
						"body"=>$body,
						"table_name"=>$this->view_name,
						"structure" => $this->structure
					);
		
		
				return $result;
		
	}

	public function getTable($key){
		global $wpdb;
		$res = $wpdb->getResults($key["table"], ARRAY_A);
		$result = array(
				"id" => $key["id"],
				"field" => $key["field"],
				"table" => $res
			);
		return $result;
	}
			
}
	

class TableORM {
	public $table_name;
	public $sql_table_name;
	public $fields;
	public $query_select;
	public $id;
	public $fields_pseudo;
	public $id_pseudo; 
	public $data_format;
	public $prefix = "timetable_";

	public function __construct($table_name){
		$this->assoc($table_name);
		
	}	

	public function showInfo(){
		return array(
			"table_name" => $this->table_name,
			"sql_table_name" => $this->sql_table_name,
			"fields"=>$this->fields,
			"id"=>$this->id,
		);	
	}

	public function getInsertArray($values){
		$arr = array_combine($this->fields,$values);
		return $arr;
	}

	public function insert($data){
		$data_insert = $this->getInsertArray($data);
		global $wpdb;
		$wpdb->insert($this->sql_table_name,$data_insert, $this->data_format);	

		return json_encode(array("id"=> $wpdb->insert_id));
		//return $this->wpdb;
		//return 1;
	}

	public function update($id, $values){
		global $wpdb;
		$keys = $this->fields;
		$data = array_combine($keys,$values);
		$wpdb->update(
				$this->sql_table_name,
				$data,
				array( $this->id =>$id ),
				$this->data_format,
				array('%d')
			);
		//return $this->wpdb;
		//return 1;
	}

	public function  findById($id){

		global $wpdb;
		$head_table = array("ID" ,"table1", "table2","table3", "table4");

		$f_arr1 = array_combine($this->fields,$this->fields_pseudo);
		
		$f_arr = array();

		foreach ($f_arr1 as $key => $value) {
			$f_arr[] = $key ." " .$value;
		}

		$f_str = implode(",",$f_arr);

		$fields = $this->id ."," . $f_str;
		//$query = "SELECT ".$fields . " FROM " . $this->sql_table_name . " WHERE " . $this->$id . " = " .$id;

		$query = "SELECT $fields FROM $this->sql_table_name WHERE $this->id = $id"; 		
		
		//return $query;	
		$results = $wpdb->get_results($query, ARRAY_A);
		if (count($results) > 0) {
			return json_encode($results[0]);		
		}
		return json_encode($results);


	}

	public function findAllQuery(){	
		$f_arr1 = array_combine($this->fields,$this->fields_pseudo);
		$f_arr = array();
		foreach ($f_arr1 as $key => $value) {
			$f_arr[] = $key ." " .$value;
		}
		$f_str = implode(",",$f_arr);
		$fields = $this->id ."," . $f_str;
		$query = "SELECT  $fields  FROM $this->sql_table_name";
		return $query; 		
	}

	public function findAllForSelect(){
		global $wpdb;
		
		$query = $this->query_select["values"];
		$results = array(
				"value"=>"",
				"values"=>$wpdb->get_results($query,ARRAY_A),
				"id"=>$this->query_select["id"],
				"field"=>$this->query_select["field"]
			);
		//return $query;
		return $results;
	}

	public function findAll($num = true){
		global $wpdb;
		$head_table = array("ID" ,"table1", "table2","table3", "table4");

		$f_arr1 = array_combine($this->fields,$this->fields_pseudo);
		
		$f_arr = array();

		foreach ($f_arr1 as $key => $value) {
			$f_arr[] = $key ." " .$value;
		}

		$f_str = implode(",",$f_arr);

		$fields = $this->id ."," . $f_str;
		$query = "SELECT  $fields  FROM $this->sql_table_name"; 		
		
		if($num){
			$results1 = $wpdb->get_results($query, ARRAY_N);
			$header = array($this->id);
			$header = array_merge($header, $this->fields_pseudo);
			$results = array(
					"head"=>$header,
					"body"=>$results1,
				);
		}else{
			$results = $wpdb->get_results($query, ARRAY_A);
		}
		return json_encode($results);
		//return $query;
		
	}

	public function remove($id){
		global $wpdb;
		$query = "DELETE FROM $this->sql_table_name WHERE $this->id = $id";
		$wpdb->query($query);
	}
	private function assoc($table_name){
		global $wpdb;
		$prefix = $this->prefix;
		$assoc_array = array(
				"test_table"=>array(
						"table_name"=> "table",
						"id" => "id",
						"id_pseudo"=>"_id",
						"fields" => array(
								"table_1",
								"table_2",
								"table_3",
								"table_4",
							),
						"data_format"=>array(
								'%s',
								'%s',
								'%s',
								'%s'
							),
						"fields_pseudo" => array(
								"table1",
								"table2",
								"table3",
								"table4",
							)
					),
					"user"=>array(
						"table_name"=> "user",
						"query_select" => array(
									"values"=>"SELECT iduser user_id, (SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name, (SELECT display_name FROM $wpdb->users WHERE ID = wp_user_id)  field FROM {$prefix}user",
									"id"=>"user_id",
									"field"=>"user_name"
								),
						"id" => "iduser",
						"id_pseudo"=>"_id",
						"fields" => array(
								'wp_user_id',
								'user_role_id'
							),
						"data_format"=>array(
								'%d',
								'%d'
							),
						"fields_pseudo" => array(
								"wp_user_id",
								"user_role_id"
							)
					),
					"user_client"=>array(
						"table_name"=> "user",
						"query_select" => array(
									"values"=>"SELECT iduser user_id, (SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name, (SELECT display_name FROM $wpdb->users WHERE ID = wp_user_id)  field FROM {$prefix}user WHERE role_id = 3" ,
									"id"=>"user_id",
									"field"=>"user_name"
								),
						"id" => "iduser",
						"id_pseudo"=>"_id",
						"fields" => array(
								'wp_user_id',
								'user_role_id'
							),
						"data_format"=>array(
								'%d',
								'%d'
							),
						"fields_pseudo" => array(
								"wp_user_id",
								"user_role_id"
							)
					),
					"user_teacher"=>array(
						"table_name"=> "user",
						"query_select" => array(
									"values"=>"SELECT iduser user_id, (SELECT display_name FROM wp_users WHERE ID = timetable_user.wp_user_id) user_name, (SELECT display_name FROM $wpdb->users WHERE ID = wp_user_id)  field FROM {$prefix}user WHERE role_id = 2",
									"id"=>"user_id",
									"field"=>"user_name"
								),
						"id" => "iduser",
						"id_pseudo"=>"_id",
						"fields" => array(
								'wp_user_id',
								'user_role_id'
							),
						"data_format"=>array(
								'%d',
								'%d'
							),
						"fields_pseudo" => array(
								"wp_user_id",
								"user_role_id"
							)
					),

					"wp_users"=>array(
						"table_name"=> "wp_users",
						"query_select" => array(
									"values"=>"SELECT ID wp_user_id, display_name, display_name field FROM $wpdb->users",
									"id"=>"wp_user_id",
									"field"=>"display_name"
								),
						"fields"=>array(),
						"fields_pseudo"=>array(),
						"id"=>"",
						"id_pseudo"=>"",
						"data_format"=>array()
					),
					"role"=>array(
						"table_name"=> "role",
						"id" => "idrole",
						"id_pseudo"=>"_id",
						"fields" => array(
								'role_name',
								'role_status'
							),
						"query_select" => array(
									"values"=>"SELECT idrole role_id, role_name, role_name field FROM {$prefix}role",
									"id"=>"role_id",
									"field"=>"role_name"
								),
						"data_format"=>array(
								'%s',
								'%d'
							),
						"fields_pseudo" => array(
								"Role",
								"RoleStatus"
							)
					),
					"teacher"=>array(
						"table_name"=> "teacher",
						"id" => "idteacher",
						"id_pseudo"=>"_id",
						"fields" => array(
								'teacher_name',
								'user_id'
							),
						
						"query_select" => array(
									"values"=>"SELECT idteacher teacher_id, teacher_name, teacher_name field FROM {$prefix}teacher",
									"id"=>"teacher_id",
									"field"=>"teacher_name"
							),
						"data_format"=>array(
								'%s',
								'%d'
							),
						"fields_pseudo" => array(
								"Name",
								"USER_ID"
							)
					),
					"client"=>array(
						"table_name"=> "client",
						"id" => "idclient",
						"id_pseudo"=>"_id",
						"fields" => array(
								'client_name',
								'user_id'
							),
						
						"query_select" => array(
									"values"=>"SELECT idclient client_id, client_name, client_name field FROM {$prefix}client",
									"id"=>"client_id",
									"field"=>"client_name"),
						"data_format"=>array(
								'%s',
								'%d'
							),
						"fields_pseudo" => array(
								"Name",
								"USER_ID"
							)
					),
					"coursestatus"=>array(
						"table_name"=> "coursestatus",
						"id" => "idcoursestatus",
						"id_pseudo"=>"_id",
						"fields" => array(
								'coursestatus_name'
							),
						"query_select" => array(
									"values"=>"SELECT idcoursestatus coursestatus_id, coursestatus_name, coursestatus_name field FROM {$prefix}coursestatus",
									"id"=>"coursestatus_id",
									"field"=>"coursestatus_name"
							),
						"data_format"=>array(
								'%s'
							),
						"fields_pseudo" => array(
								"STATUS"
							)
					),
					"paystatus"=>array(
						"table_name"=> "paystatus",
						"id" => "idpaystatus",
						"id_pseudo"=>"_id",
						"fields" => array(
								'paystatus_name'
							),
						"data_format"=>array(
								'%s'
							),
						"query_select" => array(
									"values"=>"SELECT idpaystatus paystatus_id, paystatus_name, paystatus_name field FROM {$prefix}paystatus",
									"id"=>"paystatus_id",
									"field"=>"paystatus_name"
							),
						"fields_pseudo" => array(
								"STATUS"
							)
					),
					"form"=>array(
						"table_name"=> "form",
						"id" => "idform",
						"id_pseudo"=>"_id",
						"fields" => array(
								'form_name'
							),
						"data_format"=>array(
								'%s'
							),
						"query_select" => array(
									"values"=>"SELECT idform form_id, form_name, form_name field FROM {$prefix}form",
									"id"=>"form_id",
									"field"=>"form_name"
							),
						"fields_pseudo" => array(
								"STATUS"
							)
					),
					"course"=>array(
						"table_name"=> "course",
						"id" => "idcourse",
						"id_pseudo"=>"_id",
						"fields" => array(
								'course_name',
								'course_basecost'
							),
						"query_select" => array(
									"values"=>"SELECT idcourse course_id, course_name, course_name field FROM {$prefix}course",
									"id"=>"course_id",
									"field"=>"course_name"
							),
						"data_format"=>array(
								'%s',
								'%d'
							),
						"fields_pseudo" => array(
								"Name",
								"BaseCost"
							)
					),
					"clientcourse"=>array(
						"table_name"=> "clientcourse",
						"id" => "idclientcourse",
						"id_pseudo"=>"_id",
						"fields" => array(
								"course_id",
								"paystatus_id",
								"teacher_id",
								"clientcourse_lessontotal",
								"clientcourse_count",
								"coursestatus_id",
								"client_id",
								"clientcourse_begin",
								"clientcourse_end",
								"timetable_id"
							),
						'query_select'=>array(),
						"data_format"=>array(
								'%d',
								'%d',
								'%d',	
								'%s',
								'%d',
								'%d',								
								'%d',
								'%s',
								'%s',
								'%d'
							),
						"fields_pseudo" => array(
								"courseid",
								"paystatusid",
								"teacherid",
								"clientcourselessontotal",
								"clientcoursecount",
								"coursestatusid",
								"clientid",
								"clientcoursebegin",
								"clientcourseend",
								"timetableid"
							)
					)

			);



		$tab = $assoc_array[$table_name];
		$this->table_name = $table_name;
		$this->sql_table_name = $this->prefix . $tab["table_name"];
		$this->fields = $tab["fields"];
		$this->query_select = $tab["query_select"];
		$this->fields_pseudo = $tab["fields_pseudo"];
		$this->id = $tab["id"];
		$this->id_pseudo = $tab["id_pseudo"];
		$this->data_format = $tab["data_format"];
		
	}
}


?>